package cn.com.bob.library.controller;


import cn.com.bob.library.controller.ex.PermissionException;
import cn.com.bob.library.service.ex.*;
import cn.com.bob.library.util.JsonResult;
import io.swagger.models.auth.In;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/**
 * @Author Bob
 * @Version：1.0
 * 控制层的基类，统一处理异常
 */

public class BaseController {
    //操作成功的状态码
    public  static final Integer OK = 200;


    //当产生参数值的异常会自动捕获到这里来进行统一操作
    @ExceptionHandler({ServiceException.class, PermissionException.class})
    public JsonResult<Void> exceptionHandle(Throwable e){
        JsonResult<Void> result = new JsonResult<>();

        if(e instanceof UserExistException){
            result.setState(4000);
            result.setMessage(e.getMessage());
        } else if (e instanceof UserNotExistException) {
            result.setState(4001);
            result.setMessage(e.getMessage());
        }else if (e instanceof BookNameModifyException) {
            result.setState(4002);
            result.setMessage(e.getMessage());
        }else if (e instanceof PermissionException) {
            result.setState(5000);
            result.setMessage(e.getMessage());
        }else if (e instanceof BookNotBackException) {
            result.setState(6000);
            result.setMessage(e.getMessage());
        }

        return result;
    }

    /**
     * 获取当前登录用户的uid
     * @param session:
     * @return Integer
     */
    protected final Integer getUidFromSession(HttpSession session){
        return Integer.valueOf((session.getAttribute("userId")).toString());
    }

    /**
     * 获取当前登录用户的username
     * @param session:
     * @return String
     */
    protected final String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }

    protected final Integer getPermissionFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("userPermission").toString());
    }

}
